import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'

import axios from 'axios'
interface HomeState {
	loading: boolean
	error: null | string
	list: HomeListItem[]
}

export interface HomeListItem {
	url: string
	title: string
	desc: string
	price: number
	id: string
}

export const fetchList = createAsyncThunk(
	'homeSlice/fetchList',
	async () => {
		const resp = await axios.get('/api/list')
		return resp.data
	}
)

const initialState: HomeState = {
	loading: true,
	error: null,
	list: []
}

const homeSlice = createSlice({
	name: 'homeSlice',
	initialState,	
	reducers: {},
	extraReducers: {
		[fetchList.pending.type](state) {
			state.loading = true
		},
		[fetchList.fulfilled.type](state, action) {
			state.loading = false
			state.list = action.payload.data
		}
	}
})

export default homeSlice